import React, { useEffect, useMemo, useState } from 'react';

type RecordRow = {
  id: number;
  type: 'text' | 'pest' | 'plant';
  input: string;
  output: any;
  created_at: string;
};

export const Records: React.FC = () => {
  const [rows, setRows] = useState<RecordRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [filter, setFilter] = useState<'all' | 'text' | 'pest' | 'plant'>('all');

  const fetchData = async () => {
    setLoading(true);
    setError(null);
    try {
      const q = filter === 'all' ? '' : `?type=${filter}`;
      const res = await fetch(`/api/records${q}`);
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || '获取失败');
      setRows(json as RecordRow[]);
    } catch (err: any) {
      setError(err.message || '未知错误');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [filter]);

  const onDelete = async (id: number) => {
    if (!confirm('确认删除该记录？')) return;
    try {
      const res = await fetch(`/api/records/${id}`, { method: 'DELETE' });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || '删除失败');
      setRows(prev => prev.filter(r => r.id !== id));
    } catch (err: any) {
      alert(err.message || '删除失败');
    }
  };

  const onClear = async () => {
    if (!confirm('确认清空全部记录？')) return;
    try {
      const res = await fetch(`/api/records`, { method: 'DELETE' });
      const json = await res.json();
      if (!res.ok) throw new Error(json.error || '清空失败');
      setRows([]);
    } catch (err: any) {
      alert(err.message || '清空失败');
    }
  };

  const pretty = (obj: any) => {
    try {
      return JSON.stringify(obj, null, 2);
    } catch {
      return String(obj);
    }
  };

  const titleOf = (row: RecordRow) => {
    if (!row?.output) return '';
    if (row.type === 'text' || row.type === 'pest') return row.output?.name || '';
    if (row.type === 'plant') return row.output?.name || '';
    return '';
  };

  const subtitleOf = (row: RecordRow) => {
    if (!row?.output) return '';
    if (row.type === 'text' || row.type === 'pest') return row.input;
    if (row.type === 'plant') return row.input;
    return '';
  };

  const filtered = useMemo(() => rows, [rows]);

  return (
    <div className="card">
      <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
        <div style={{ fontWeight: 700 }}>识别记录</div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <select value={filter} onChange={(e) => setFilter(e.target.value as any)}>
            <option value="all">全部类型</option>
            <option value="text">文字问答</option>
            <option value="pest">病虫害</option>
            <option value="plant">植物</option>
          </select>
          <button onClick={fetchData} disabled={loading}>{loading ? '刷新中...' : '刷新'}</button>
          <button onClick={onClear}>清空全部</button>
        </div>
      </div>

      {error && <div className="error">{error}</div>}

      <div className="card" style={{ padding: 0 }}>
        <div style={{ overflow: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ textAlign: 'left', borderBottom: '1px solid var(--border)' }}>
                <th style={{ padding: '10px 12px' }}>ID</th>
                <th style={{ padding: '10px 12px' }}>类型</th>
                <th style={{ padding: '10px 12px' }}>标题</th>
                <th style={{ padding: '10px 12px' }}>输入</th>
                <th style={{ padding: '10px 12px' }}>创建时间</th>
                <th style={{ padding: '10px 12px' }}>操作</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(r => (
                <tr key={r.id} style={{ borderTop: '1px solid var(--border)' }}>
                  <td style={{ padding: '10px 12px' }}>{r.id}</td>
                  <td style={{ padding: '10px 12px' }}><span className="tag">{r.type}</span></td>
                  <td style={{ padding: '10px 12px' }}>{titleOf(r)}</td>
                  <td style={{ padding: '10px 12px', maxWidth: 420, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{subtitleOf(r)}</td>
                  <td style={{ padding: '10px 12px', color: '#9aa4d3' }}>{r.created_at}</td>
                  <td style={{ padding: '10px 12px' }}><button onClick={() => onDelete(r.id)}>删除</button></td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr>
                  <td colSpan={6} style={{ padding: '12px' }}>暂无记录</td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

